package cn.qdu.service;

import cn.qdu.dao.LikeDao;
import cn.qdu.model.Like;
import cn.qdu.model.User;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class LikeService {
    private LikeDao likeDao;

    public LikeService(LikeDao likeDao) {
        this.likeDao = likeDao;
    }

    /**
     * 点赞/取消点赞
     * @param postId 日志ID
     * @param userId 用户ID
     * @return true表示点赞成功，false表示取消点赞
     */
    public boolean toggleLike(int postId, String userId) throws SQLException {
        // 检查是否已点赞
        boolean isLiked = likeDao.checkLikeExists(postId, userId, "like");

        if (isLiked) {
            // 已点赞 → 执行取消
            likeDao.deleteLike(postId, userId);
            return false;
        } else {
            // 未点赞 → 执行点赞
            Like like = new Like();
            like.setPostId(postId);
            like.setUserId(userId);
            like.setType("like");
            likeDao.addLike(like);
            return true;
        }
    }

    /**
     * 检查用户是否已点赞
     */
    public boolean isLiked(int postId, String userId) throws SQLException {
        // 由于LikeDao没有直接提供check方法，我们通过获取列表来判断
        List<Like> likes = likeDao.getLikesByPostId(postId);
        for (Like like : likes) {
            if (like.getUserId().equals(userId) && "like".equals(like.getType())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取点赞数
     */
    public int getLikeCount(int postId) throws SQLException {
        return likeDao.getLikeCountByPostId(postId, "like");
    }

    /**
     * 获取点赞用户列表
     */
    public List<Like> getLikes(int postId) throws SQLException {
        return likeDao.getLikesByPostId(postId).stream()
                .filter(like -> "like".equals(like.getType()))
                .collect(Collectors.toList());
    }
}